package com.mayikt.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mayikt.entity.Content;
import com.mayikt.entity.Doc;
import com.mayikt.entity.DocExample;
import com.mayikt.exception.BusinessException;
import com.mayikt.exception.BusinessExceptionCode;
import com.mayikt.mapper.ContentMapper;
import com.mayikt.mapper.DocMapper;
import com.mayikt.mapper.DocMapperCust;
import com.mayikt.req.DocQueryReq;
import com.mayikt.req.DocSaveReq;
import com.mayikt.resp.DocQueryResp;
import com.mayikt.resp.PageResp;
import com.mayikt.utils.CopyUtil;
import com.mayikt.utils.RedisTemplateUtils;
import com.mayikt.utils.RequestContext;
import com.mayikt.utils.SnowFlake;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DocService {
    @Resource
    private DocMapper docMapper;
    @Resource
    private DocMapperCust docMapperCust;
    @Resource
    private ContentMapper contentMapper;
    @Resource
    private SnowFlake snowFlake;
    @Resource
    private RedisTemplateUtils redisTemplateUtils;
    @Resource
    private WebSocketService webSocketService;

    /**
     * 分页查询
     * @param docQueryReq
     * @return
     */
    public PageResp<DocQueryResp> list(DocQueryReq docQueryReq) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();

        // 判断 name 条件是否为空
        if(!ObjectUtils.isEmpty(docQueryReq.getName())) {
            criteria.andNameLike("%" + docQueryReq.getName() + "%");
        }

        // 分页
        PageHelper.startPage(docQueryReq.getPage(), docQueryReq.getSize());
        List<Doc> docList = docMapper.selectByExample(docExample);
        PageInfo<Doc> pageInfo = new PageInfo<>(docList);

        // do 转 dto
        List<DocQueryResp> docResps = CopyUtil.copyList(docList, DocQueryResp.class);

        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(docResps);

        return pageResp;
    }

    /**
     * 查询当前电子书下的所有文档
     * @return
     */
    public List<DocQueryResp> all(Long ebookId) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andEbookIdEqualTo(ebookId);
        // 排序
        docExample.setOrderByClause("sort asc");

        List<Doc> docList = docMapper.selectByExample(docExample);

        // do 转 dto
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;
    }

    @Transactional
    public void save(DocSaveReq docSaveReq) {
        Doc doc = CopyUtil.copy(docSaveReq, Doc.class);
        Content content = CopyUtil.copy(docSaveReq, Content.class);
        if(ObjectUtils.isEmpty(docSaveReq.getId())) {
            // 雪花算法 生成id
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0);
            doc.setVoteCount(0);
            // 新增文档信息
            docMapper.insert(doc);
            // 新增文档内容
            content.setId(doc.getId());
            contentMapper.insert(content);
        } else {
            // 更新
            docMapper.updateByPrimaryKey(doc);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if(count == 0) {
                contentMapper.insert(content);
            }
        }
    }

    @Transactional
    public int delete(List<String> ids) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        // 批量删除
        criteria.andIdIn(ids);
        return docMapper.deleteByExample(docExample);
    }

    @Transactional
    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        // 文档阅读数+1
        docMapperCust.increaseViewCount(id);
        if(!ObjectUtils.isEmpty(content)) {
            return content.getContent();
        }
        return "";
    }

    /**
     * 点赞
     * @param id
     */
    public void vote(Long id) {
        // 远程ip + doc.id 作为key，24小时不能重复
        String ip = RequestContext.getRemoteAddr();
        if(redisTemplateUtils.validateRepeat("DOC_VOTE_" + id + "_" + ip,3600 * 24L)) {
            docMapperCust.increaseVoteCount(id);
            // WebSocket 推送消息
            Doc docDb = docMapper.selectByPrimaryKey(id);
            String logId = MDC.get("LOG_ID");
            webSocketService.sendInfo("【" + docDb.getName() + "】被点赞！", logId);
        } else {
            // 提示您已点赞过
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
    }

    /**
     * 根据文档表 更新电子书的文档数，点赞数，阅读数
     */
    public void updateEbookInfo() {
        docMapperCust.updateEbookInfo();
    }
}
